package com.taotao.rest.controller;

import com.taotao.pojo.Content;
import com.taotao.rest.dao.JedisClient;
import com.taotao.rest.service.ContentService;
import com.taotao.util.JsonUtils;
import com.taotao.util.TaotaoResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * describe:
 *
 * @author hong.zheng
 * @date 2018/09/16
 */
@Controller
@RequestMapping("/content")
public class ContentController {

    @Autowired
    private ContentService contentService;

    @Autowired
    private JedisClient jedisClient;

    @Value("${INDEX_CONTENT_REDIS_KEY}")
    private String INDEX_CONTENT_REDIS_KEY;


    @RequestMapping("/category/{cid}")
    @ResponseBody
    public TaotaoResult getContentList(@PathVariable Long cid) {
        TaotaoResult result = TaotaoResult.ok();
        try {
            //从缓存中取内容
            try {
                String contentListStr = jedisClient.hget(INDEX_CONTENT_REDIS_KEY, cid + "");
                if (!StringUtils.isBlank(contentListStr)) {
                    //把字符串转换成list
                    List<Content> resultList = JsonUtils.jsonToList(contentListStr, Content.class);
                    result.setData(resultList);
                    return result;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            List<Content> contentList = contentService.getContentList(cid);
            try {
                //把list转换成字符串
                String cacheString = JsonUtils.objectToJson(contentList);
                jedisClient.hset(INDEX_CONTENT_REDIS_KEY, cid + "", cacheString);
            } catch (Exception e) {
                e.printStackTrace();
            }
            result.setData(contentList);
        } catch (Exception e) {
            e.printStackTrace();
            return TaotaoResult.build(500, e.getMessage());
        }
        return result;
    }
}
